package com.lanou3g.dllo.baidumusic.main.playmusic;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.lanou3g.dllo.baidumusic.R;
import com.lanou3g.dllo.baidumusic.database.RecentlyPlay;
import com.lanou3g.dllo.baidumusic.database.SingleLiteOrm;
import com.lanou3g.dllo.baidumusic.event.IndexEvent;
import com.lanou3g.dllo.baidumusic.event.ProgressEvent;
import com.lanou3g.dllo.baidumusic.event.SongIdEvent;
import com.lanou3g.dllo.baidumusic.main.MainActivity;
import com.lanou3g.dllo.baidumusic.tools.MyVolley;
import com.lanou3g.dllo.baidumusic.tools.PlaylistManager;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by dllo on 16/6/24.
 */

public class PlayMusicService extends Service {

    private MediaPlayer player;
    private MyBinder binder = new MyBinder();
    private SongPlayBean songPlayBean;
    private int index;
    private int pattern = 0;
    private long duration;
    private String playTime;
    private RemoteViews remoteViews;
    private String songsImgUrl, songName, songAuthor;
    private NotificationManager manager;
    private PreBroadcastReceiver preBroadcastReceiver;
    private PauseBroadcastReceiver pauseBroadcastReceiver;
    private NextBroadcastReceiver nextBroadcastReceiver;
    private CloseBroadcastReceiver closeBroadcastReceiver;

    private static final int LIST_LOOP = 0; // 列表
    private static final int SINGLE_LOOP = 1; // 单曲
    private static final int RANDOM_PLAY = 2; // 随机
    private static final int ORDER_PLAY = 3; // 顺序

    @Override
    public void onCreate() {
        // 注册EventBus
        EventBus.getDefault().register(this);
        super.onCreate();
        if (player == null) {
            player = new MediaPlayer();
        }
        // 为Media Player的播放完成事件绑定事件监听器
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // 自动播放下一首
                binder.playNext(pattern);
            }
        });

        // 线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (player.isPlaying()) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
                        playTime = simpleDateFormat.format(new Date(player.getCurrentPosition()));
                        // 获得歌曲的持续时间
                        binder.setDuration(player.getDuration());
                        // 发送播放时间的EventBus
                        EventBus.getDefault().post(new ProgressEvent(player.getCurrentPosition(), playTime));
                        EventBus.getDefault().post(songPlayBean);
                    }
                    // 发送暂停播放的EventBus
                    EventBus.getDefault().post(new PlayOrPause(player.isPlaying()));

                }

            }
        }).start();

        // 注册,接收广播
        preBroadcastReceiver = new PreBroadcastReceiver();
        IntentFilter filterPre = new IntentFilter();
        filterPre.addAction(getPackageName() + ".PRE");
        registerReceiver(preBroadcastReceiver, filterPre);

        pauseBroadcastReceiver = new PauseBroadcastReceiver();
        IntentFilter filterPlay = new IntentFilter();
        filterPlay.addAction(getPackageName() + ".PLAY");
        registerReceiver(pauseBroadcastReceiver, filterPlay);

        nextBroadcastReceiver = new NextBroadcastReceiver();
        IntentFilter filterNext = new IntentFilter();
        filterNext.addAction(getPackageName() + ".NEXT");
        registerReceiver(nextBroadcastReceiver, filterNext);

        closeBroadcastReceiver = new CloseBroadcastReceiver();
        IntentFilter filterClose = new IntentFilter();
        filterClose.addAction(getPackageName() + ".CLOSE");
        registerReceiver(closeBroadcastReceiver, filterClose);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class MyBinder extends Binder {
        // 播放下一曲
        public void playNext(int pattern) {

            switch (pattern) {
                // 列表循环
                case LIST_LOOP:
                    index++;
                    // 播到最后一首时,回到第一首
                    if (index >= PlaylistManager.getInstance().getPlaylist().size()) {
                        index = 0;
                    }
                    playSelectedSongs(new SongIdEvent(PlaylistManager.getInstance().getPlaylist().get(index).getSongId()));
                    break;
                // 单曲循环
                case SINGLE_LOOP:
                    playSelectedSongs(new SongIdEvent(PlaylistManager.getInstance().getPlaylist().get(index).getSongId()));
                    break;
                // 随机播放
                case RANDOM_PLAY:
                    Random random = new Random();
                    index = random.nextInt(PlaylistManager.getInstance().getPlaylist().size());
                    playSelectedSongs(new SongIdEvent(PlaylistManager.getInstance().getPlaylist().get(index).getSongId()));
                    break;
                // 顺序播放
                case ORDER_PLAY:
                    index++;
                    // 当歌曲放到最后一首,回到第一首
                    if (index < PlaylistManager.getInstance().getPlaylist().size()) {
                        playSelectedSongs(new SongIdEvent(PlaylistManager.getInstance().getPlaylist().get(index).getSongId()));
                    } else {
                        player.stop();
                    }
                    break;
            }
        }

        // 暂停/播放
        public void playPause() {
            if (!player.isPlaying()) {
                player.start();
                // 外部点击暂停播放,按钮也可跟随一起变化
                showNotification(songsImgUrl, songName, songAuthor, R.mipmap.bt_notificationbar_pause);
            } else if (player.isPlaying() && player != null) {
                player.pause();
                showNotification(songsImgUrl, songName, songAuthor, R.mipmap.bt_notificationbar_play);
            }
        }

        // 播放上一首
        public void playPre() {
            if (index <= 0) {
                Toast.makeText(PlayMusicService.this, "已经是第一首了", Toast.LENGTH_SHORT).show();
            } else {
                index--;
                playSelectedSongs(new SongIdEvent(PlaylistManager.getInstance().getPlaylist().get(index).getSongId()));
            }
        }
        // 停止方法
        public void playStop() {
            player.stop();
        }

        // 正在播放的位置
        public boolean playingPosition(int position) {
            return index == position;
        }

        // 设置播放模式
        public void setPattern(int mPattern) {
            pattern = mPattern;
        }

        // 获得播放模式
        public int getPattern() {
            return pattern;
        }

        // 歌曲时间
        public void setDuration(long mDuration) {
            duration = mDuration;
        }

        public long getDuration() {
            return duration;
        }

        // 播放时间
        public String getPlayTime() {
            return playTime;
        }

        // 进度
        public void setProgress(int progress) {
            player.seekTo(progress);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        unregisterReceiver(preBroadcastReceiver);
        unregisterReceiver(pauseBroadcastReceiver);
        unregisterReceiver(nextBroadcastReceiver);
        unregisterReceiver(closeBroadcastReceiver);
        super.onDestroy();
        player.stop();
        player.release();
    }

    // 播放点击的歌曲
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void playSelectedSongs(SongIdEvent songsIdEvent) {
        String songsId = songsIdEvent.getSongId();
        String songUrl = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=webapp_music&method=baidu.ting.song.play&format=json&callback=&songid="
                + songsId + "&_=1413017198449";
        MyVolley.getMyVolley().initGson(songUrl, new MyVolley.GetGsonListener<SongPlayBean>() {
            @Override
            public void getGsonListener(SongPlayBean data) {
                songPlayBean = data;
                player.reset();

                // 通知栏信息
                songsImgUrl = songPlayBean.getSonginfo().getPic_small();
                songName = songPlayBean.getSonginfo().getTitle();
                songAuthor = songPlayBean.getSonginfo().getAuthor();
                // 当MediaPlayer调用prepare()方法时触发该监听器
                player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        player.start();
                        showNotification(songsImgUrl, songName, songAuthor, R.mipmap.bt_notificationbar_pause);
                        addToRecentltPlay();
                    }
                });

                try {
                    player.setDataSource(songPlayBean.getBitrate().getFile_link());
                    player.prepareAsync();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, SongPlayBean.class);
    }

    // 添加到数据库中的最近播放列表里
    public void addToRecentltPlay() {
        if (SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(RecentlyPlay.class).size() == 0) {
            SingleLiteOrm.getSingleLiteOrm().getLiteOrm().insert(new RecentlyPlay(songPlayBean.getSonginfo()
                    .getSong_id(), songPlayBean.getSonginfo().getTitle(), songPlayBean.getSonginfo().getAuthor()));
        } else {
            QueryBuilder<RecentlyPlay> queryBuilder = new QueryBuilder<>(RecentlyPlay.class);
            queryBuilder.whereEquals("songName", songPlayBean.getSonginfo().getTitle());
            if (SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(queryBuilder).size() == 0) {
                SingleLiteOrm.getSingleLiteOrm().getLiteOrm().insert(new RecentlyPlay(songPlayBean.getSonginfo()
                        .getSong_id(), songPlayBean.getSonginfo().getTitle(), songPlayBean.getSonginfo().getAuthor()));
            }
        }
        // 发送广播,刷新我的界面的最近播放歌曲数
        Intent intent = new Intent(getPackageName() + ".REFRESHRECRNTLYPLAY");
        sendBroadcast(intent);
    }

    @Subscribe
    public void IndexEvent(IndexEvent indexEvent) {
        index = indexEvent.getIndex();
    }

    // 通知栏
    public void showNotification(String songsImgUrl, String songName, String songAuthor, int id) {

        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.log);
        builder.setAutoCancel(true);

        remoteViews = new RemoteViews(getPackageName(), R.layout.notification_layout);
        remoteViews.setTextViewText(R.id.notification_songname, songName);
        remoteViews.setTextViewText(R.id.notification_singer, songAuthor);
        remoteViews.setImageViewResource(R.id.notification_pause, id);

        Intent intentPlay = new Intent(getPackageName() + ".PLAY");
        Intent intentNext = new Intent(getPackageName() + ".NEXT");
        Intent intentClose = new Intent(getPackageName() + ".CLOSE");
        Intent intentPre = new Intent(getPackageName() + ".PRE");
        Intent intentShow = new Intent(this, MainActivity.class);
        // 发广播
        PendingIntent pendingIntentNext = PendingIntent.getBroadcast(this, 2011, intentNext, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pendingIntentClose = PendingIntent.getBroadcast(this, 2012, intentClose, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pendingIntentPre = PendingIntent.getBroadcast(this, 2013, intentPre, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pendingIntentPlay = PendingIntent.getBroadcast(this, 2014, intentPlay, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pendingIntentShow = PendingIntent.getActivity(this, 2015, intentShow, PendingIntent.FLAG_UPDATE_CURRENT);

        remoteViews.setOnClickPendingIntent(R.id.notification_pause, pendingIntentPlay);
        remoteViews.setOnClickPendingIntent(R.id.notification_nextsong, pendingIntentNext);
        remoteViews.setOnClickPendingIntent(R.id.notification_close, pendingIntentClose);
        remoteViews.setOnClickPendingIntent(R.id.notification_presong, pendingIntentPre);
        remoteViews.setOnClickPendingIntent(R.id.notification_relativelayout, pendingIntentShow);

        builder.setContent(remoteViews);
        Notification notification = builder.build();
        manager.notify(2016, notification);

        if (songsImgUrl != null && songsImgUrl.length() > 0) {
            Picasso.with(this).load(songsImgUrl).into(remoteViews, R.id.notification_photo, 2016, notification);
        } else {
            remoteViews.setImageViewResource(R.id.notification_photo, R.mipmap.log);
        }

    }

    // 上一曲的广播
    class PreBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            binder.playPre();
        }
    }

    // 暂停播放的广播
    class PauseBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (player.isPlaying()) {
                binder.playPause();
                showNotification(songsImgUrl, songName, songAuthor, R.mipmap.bt_notificationbar_play);
            } else {
                player.start();
                showNotification(songsImgUrl, songName, songAuthor, R.mipmap.bt_notificationbar_pause);
            }
        }
    }

    // 下一曲的广播
    class NextBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            binder.playNext(pattern);
        }
    }

    // 退出的广播
    class CloseBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 退出程序及notification
            if (manager != null) {
                manager.cancel(2016);
            }
            System.exit(0);
        }
    }


}
